package com.splant.android.smart.UILevel.Community;

import android.Manifest;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.app.FragmentManager;
import android.app.Fragment;
import android.support.v4.app.ActivityCompat;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.WeatherDeviceInfoBean;
import com.splant.android.smart.ModelLevel.WeatherInfoBean;
import com.splant.android.smart.SystemDefinedLevel.AutoUpdateSoft.SoftVersionManager;
import com.splant.android.smart.SystemDefinedLevel.SlidingLayout.SlidingLayout;
import com.splant.android.smart.UILevel.Community.fragments.Garden_Devices_Fragment;
import com.splant.android.smart.UILevel.Community.fragments.Garden_Ency_Fragment;
import com.splant.android.smart.UILevel.Community.fragments.Garden_Me_Fragment;
import com.splant.android.smart.UILevel.Community.fragments.Garden_Plants_Fragment;
import org.apache.http.Header;
import org.json.JSONObject;

public class Garden_Main_Activity extends Activity {

    /**
     * 侧滑布局对象，用于通过手指滑动将左侧的菜单布局进行显示或隐藏。
     */
    private SlidingLayout slidingLayout;

    /**
     * menu按钮，点击按钮展示左侧布局，再点击一次隐藏左侧布局。
     */

    private LinearLayout ll_content;
    private RadioGroup rdoGp_changeMenu;
    private FragmentManager fm;
    private RadioButton rdoBtn_plants;
    private RadioButton rdoBtn_devices;
    private RadioButton rdoBtn_ency;
    private RadioButton rdoBtn_me;

    private TextView tv_abnormal;
    private TextView tv_city;
    private TextView tv_weatherDesc;
    private TextView tv_tempRange;
    private TextView tv_tempture;
    private TextView tv_humidity;
    private TextView tv_wind;
    private TextView tv_illumination;
    private TextView tv_rainfall;
    private TextView tv_pm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.garden_main_activity);

        slidingLayout = (SlidingLayout) findViewById(R.id.slidingLayout);
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        rdoGp_changeMenu = (RadioGroup) findViewById(R.id.rdoGp_changeMenu);

        rdoBtn_plants = (RadioButton) findViewById(R.id.rdoBtn_plants);
        rdoBtn_devices = (RadioButton) findViewById(R.id.rdoBtn_devices);
        rdoBtn_ency = (RadioButton) findViewById(R.id.rdoBtn_ency);
        rdoBtn_me = (RadioButton) findViewById(R.id.rdoBtn_me);
        tv_abnormal= (TextView) findViewById(R.id.tv_abnormal);

        tv_city= (TextView) findViewById(R.id.tv_city);
        tv_weatherDesc= (TextView) findViewById(R.id.tv_weatherDesc);
        tv_tempRange= (TextView) findViewById(R.id.tv_tempRange);
        tv_tempture= (TextView) findViewById(R.id.tv_tempture);
        tv_humidity= (TextView) findViewById(R.id.tv_humidity);
        tv_wind= (TextView) findViewById(R.id.tv_wind);
        tv_illumination= (TextView) findViewById(R.id.tv_illumination);
        tv_rainfall= (TextView) findViewById(R.id.tv_rainfall);
        tv_pm= (TextView) findViewById(R.id.tv_pm);

        slidingLayout.setScrollEvent(ll_content);
        slidingLayout.setState(iswitch);

        fm = getFragmentManager();

        init();

        rdoGp_changeMenu.setOnCheckedChangeListener(menuChangeChick);
    }

    private Fragment plants;

    private void init() {

        plants = fm.findFragmentByTag("plants");

        if (plants == null) {

            FragmentTransaction ft = fm.beginTransaction();
            plants = new Garden_Plants_Fragment();

            ((Garden_Plants_Fragment) plants).setSlidingLayout(slidingLayout);

            ft.add(R.id.fl_container, plants, "plants");
            ft.commit();

            rdoBtn_plants.setBackgroundResource(R.color.garden_color3);
        }

        Global.selectedArea=null;

        if (Global.isInit)
        {
            currentapiVersion = android.os.Build.VERSION.SDK_INT;
            verifyStoragePermissions(this);

            checkSoftVersion();

            Global.isInit=false;
        }

    }

    private SlidingLayout.Iswitch iswitch = new SlidingLayout.Iswitch() {
        @Override
        public void updateState(boolean state) {

            if (rdoGp_changeMenu.getCheckedRadioButtonId() == R.id.rdoBtn_plants) {
                if (plants != null)
                {

                    ((Garden_Plants_Fragment) plants).updateMenuIconState(state);
                    if (isGetWeatherInfo==false)
                    {
                        tv_city.setText(Global.user.getCity());

                        getWeatherInfo();
                    }
                }
            }
        }
    };


    private boolean isGetWeatherInfo=false;
    private sPlantAsyncHttpClient sPlantClient ;

    private void getWeatherInfo()
    {
        sPlantClient = sPlantAsyncHttpClient.getInstance();
        RequestParams params=new RequestParams();
        params.put("userId", Global.user.getUserId());

        sPlantClient.get(sPlantAsyncHttpClient.GETWEATHERCONDITION,params,new sPlantJsonHttpResponseHandler()
                {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try
                        {

                            if (response.getInt("succeed") == 1) {

                                Gson gson=new Gson();
                                WeatherInfoBean weatherInfo=gson.fromJson(response.toString(),WeatherInfoBean.class);

                                if (weatherInfo.getWeather()!=null)
                                {
                                    tv_weatherDesc.setText(weatherInfo.getWeather().getWeatherDesc());
                                    tv_tempRange.setText(weatherInfo.getWeather().getTempRange());
                                    tv_humidity.setText(weatherInfo.getWeather().getHumidity());
                                }
                                isGetWeatherInfo=true;
                                getWeatherDeviceInfo();
                            }
                        }
                        catch (Exception e)
                        {

                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        Toast.makeText(Garden_Main_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                }
        );

    }

    private void getWeatherDeviceInfo()
    {
        RequestParams params=new RequestParams();
        params.put("userId", Global.user.getUserId());

        sPlantClient.get(sPlantAsyncHttpClient.GETMETEOROLOGICALINFO,params,new sPlantJsonHttpResponseHandler()
                {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try
                        {

                            if (response.getInt("succeed") == 1) {

                                Gson gson=new Gson();
                                WeatherDeviceInfoBean weatherInfo=gson.fromJson(response.toString(),WeatherDeviceInfoBean.class);

                                if(weatherInfo.getWeatherInfo()!=null)
                                {
                                    tv_tempture.setText(weatherInfo.getWeatherInfo().getTemperature());
                                    tv_humidity.setText(weatherInfo.getWeatherInfo().getHumidity());
                                    tv_wind.setText(weatherInfo.getWeatherInfo().getWindSpeed());
                                    tv_illumination.setText(weatherInfo.getWeatherInfo().getIllumination());
                                    tv_rainfall.setText(weatherInfo.getWeatherInfo().getWeatherDesc());
                                    tv_pm.setText(weatherInfo.getWeatherInfo().getPm());
                                }

                            }
                            else if (response.getInt("succeed") ==0)
                            {

                            }
                        }
                        catch (Exception e)
                        {

                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        Toast.makeText(Garden_Main_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                }
        );

    }


    private RadioGroup.OnCheckedChangeListener menuChangeChick = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            FragmentTransaction ft = fm.beginTransaction();
            Fragment plants = fm.findFragmentByTag("plants");
            Fragment devices = fm.findFragmentByTag("devices");
            Fragment ency = fm.findFragmentByTag("ency");
            Fragment me = fm.findFragmentByTag("me");

            if (plants != null)
                ft.hide(plants);

            if (devices != null)
                ft.hide(devices);

            if (ency != null)
                ft.hide(ency);

            if (me != null)
                ft.hide(me);

            rdoBtn_plants.setBackgroundResource(R.color.garden_color2);
            rdoBtn_devices.setBackgroundResource(R.color.garden_color2);
            rdoBtn_ency.setBackgroundResource(R.color.garden_color2);
            rdoBtn_me.setBackgroundResource(R.color.garden_color2);

            switch (checkedId) {

                case R.id.rdoBtn_plants:

                    if (plants == null) {
                        plants = new Garden_Plants_Fragment();
                        ft.add(R.id.fl_container, plants, "plants");
                    } else
                        ft.show(plants);

                    rdoBtn_plants.setBackgroundResource(R.color.garden_color3);
                    break;

                case R.id.rdoBtn_devices:
                    if (devices == null) {
                        devices = new Garden_Devices_Fragment();
                        ft.add(R.id.fl_container, devices, "devices");
                    } else
                        ft.show(devices);

                    rdoBtn_devices.setBackgroundResource(R.color.garden_color3);
                    break;
                case R.id.rdoBtn_ency:
                    if (ency == null) {
                        ency = new Garden_Ency_Fragment();
                        ft.add(R.id.fl_container, ency, "ency");
                    } else
                        ft.show(ency);

                    rdoBtn_ency.setBackgroundResource(R.color.garden_color3);
                    break;
                case R.id.rdoBtn_me:

                    if (me == null) {
                        me = new Garden_Me_Fragment();
                        ft.add(R.id.fl_container, me, "me");
                    } else
                        ft.show(me);

                    rdoBtn_me.setBackgroundResource(R.color.garden_color3);
                    break;
            }
            ft.commit();
        }
    };

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    private int currentapiVersion;
    public static void verifyStoragePermissions(Activity activity) {

        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }

    }

    private void checkVersionUpdate() {

        SoftVersionManager softVersionManager = new SoftVersionManager(this);
        softVersionManager.checkVersion(false);

    }

    private void checkSoftVersion() {
        if (currentapiVersion<23)
            checkVersionUpdate();
        else
        {
            int permission = ActivityCompat.checkSelfPermission(Garden_Main_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission==PackageManager.PERMISSION_GRANTED)
            {
                checkVersionUpdate();
            }
        }
    }


}
